<template>
    <view
        class="byt-guess"
        v-if="displayItems && displayItems.length > 0"
        :style="{position: 'relative' }"
    >
        <view class="byt-guess__title" style="z-index: 10">
            <view class="byt-guess__title-left">
                <!-- <basic-image width="60rpx" height="60rpx" src="https://img.yummall.cn/baiyetong/byt-uni-ui/guess_icon.svg"></basic-image> -->
                <image
                    style="width: 60rpx; height: 60rpx"
                    :src="colorIcon.guessIcon ? colorIcon.guessIcon : 'https://img.yummall.cn/baiyetong/byt-uni-ui/guess_icon.svg'"
                    mode=""
                ></image>
                <view class="byt-guess__title-left__icon" style="font-weight: bold">我能帮您做什么</view>
            </view>
            <view class="byt-guess__title-right" @click="onChange" v-if="showChangeButton">
                <image
                    style="width: 32rpx; height: 32rpx"
                    :src="colorIcon.guessChange ? colorIcon.guessChange : 'https://img.yummall.cn/baiyetong/byt-uni-ui/guess_change.svg'"
                    mode=""
                ></image>

                <view class="byt-guess__title-right__icon" :style="{ color: colorIcon.guessChangeColor ? colorIcon.guessChangeColor : '#448ef7' }">换一换</view>
            </view>
            
        </view>
        <view class="byt-guess__tab" style="z-index: 10">
            <!--  <view style="padding: 24rpx">
                <scroll-view :scroll-x="true">
                    <view class="byt-guess__tab-box">
                        <view
                            class="byt-guess__tab-btn"
                            :class="{ 'is-active': problemCategoryKey === key }"
                            v-for="(value, key) in problemList"
                            @click="categoryClick(key)"
                            :key="key"
                            :style="{
                                background: problemCategoryKey === key ? (colorIcon.mainColor ? colorIcon.mainColor : '#448ef7') : '',
                                borderColor: problemCategoryKey === key ? (colorIcon.mainColor ? colorIcon.mainColor : '#448ef7') : ''
                            }"
                        >
                            <text>{{ key }}</text>
                        </view>
                    </view>
                </scroll-view>
            </view> -->

            <!-- 简化的数据显示逻辑 -->
            <view class="byt-guess__tabpane-item" v-for="(item, index) in displayItems" :key="index" @click="problemClick(getItemText(item))">
                <view class="byt-guess__tabpane-item__index">{{ index + 1 }}.{{ getItemText(item) }}</view>
                <basic-icon name="arrow-right" size="24rpx"></basic-icon>
            </view>
        </view>
    </view>
</template>

<script>
// import { BasicImage, BasicIcon } from '../../basic';
// 图标
import BasicIcon from '../../basic/basic-icon/basic-icon.vue';

import { isEmpty } from '../../../utils/index.js';
export default {
    name: 'Prompts',
    components: {
        BasicIcon
    },
    emits: ['itemClick', 'change'],
    props: {
        // 主题色和图标
        colorIcon: {
            type: Object,
            default: () => {
                return {
                    // 主题色
                    mainColor: '#448ef7',
                    // 猜你想问换一换 字体颜色
                    guessChangeColor: '#1890ff',
                    // 猜你想问背景颜色
                    guessBgColor: '-webkit-linear-gradient(top, #dff6ff99, #ffffff 200rpx)',
                    // 猜你想问换一换图标
                    guessChange: 'https://img.yummall.cn/baiyetong/byt-uni-ui/guess_change.svg',
                    //猜你想问文字头部左边图标
                    guessIcon: 'https://img.yummall.cn/baiyetong/byt-uni-ui/guess_icon.svg'
                };
            }
        },
        // 推荐问题数据列表
        items: {
            type: Array,
            default: () => []
        },
        // 常用话术键值（用于从对象中提取文本）
        textKey: {
            type: String,
            default: 'text'
        },
        // 是否支持换一换功能（外部控制）
        supportChange: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            currentIndex: 0  // 换一换功能的当前索引
        };
    },
    computed: {
        // 当前显示的数据
        displayItems() {
            const items = this.items || [];
            
            // 如果支持换一换且是分组数据，返回当前分组
            if (this.supportChange && this.isGroupedData) {
                const groups = this.getGroups();
                const groupKeys = Object.keys(groups);
                if (groupKeys.length > 0) {
                    const currentKey = groupKeys[this.currentIndex % groupKeys.length];
                    return groups[currentKey] || [];
                }
            }
            
            // 否则直接返回所有数据
            return items;
    },
        
        // 是否为分组数据
        isGroupedData() {
            return this.items.length > 0 && 
                   typeof this.items[0] === 'object' && 
                   this.items[0].group !== undefined;
        },
        
        // 是否显示换一换按钮
        showChangeButton() {
            if (!this.supportChange) return false;
            
            if (this.isGroupedData) {
                const groups = this.getGroups();
                return Object.keys(groups).length > 1;
            }
            
            return false;
        }
    },
    mounted() {
        // 暴露调试方法到组件实例
        this.$nextTick(() => {
            if (typeof window !== 'undefined') {
                // 全局调试方法
                window.debugPromptsInternal = () => {
                    this.debugPromptsData();
                };
            }
        });
    },
    methods: {
        isEmpty,
        // 获取分组数据
        getGroups() {
            if (!this.isGroupedData) return {};
            
            const groups = {};
            this.items.forEach(item => {
                const groupKey = item.group || 'default';
                if (!groups[groupKey]) {
                    groups[groupKey] = [];
                }
                groups[groupKey].push(item);
            });
            
            return groups;
        },
        // 智能提取文本内容的方法
        getItemText(item) {
            if (!item) return '';
            
            // 如果是字符串，直接返回
            if (typeof item === 'string') return item;
            
            // 如果是对象，按优先级查找文本字段
            if (typeof item === 'object') {
                // 优先使用配置的 textKey
                if (item[this.textKey]) return item[this.textKey];
                
                // 常见的文本字段名
                const textFields = ['text', 'name', 'title', 'label', 'content'];
                for (const field of textFields) {
                    if (item[field]) return item[field];
                }
                
                // 如果都没有，返回对象的第一个字符串值
                const values = Object.values(item);
                for (const value of values) {
                    if (typeof value === 'string' && value.trim()) {
                        return value;
                    }
                }
            }
            
            return '未知内容';
        },
        // 调试方法
        debugPromptsData() {
            console.log('🔍 Prompts组件完整调试信息:');
            console.log('===============================');
            console.log('📥 输入数据:');
            console.log('  - items传入的数据:', this.items);
            console.log('  - textKey:', this.textKey);
            console.log('  - supportChange:', this.supportChange);
            
            console.log('🔄 内部状态:');
            console.log('  - currentIndex:', this.currentIndex);
            console.log('  - isGroupedData:', this.isGroupedData);
            
            if (this.isGroupedData) {
                const groups = this.getGroups();
                const groupKeys = Object.keys(groups);
                console.log('🔑 分组分析:');
                console.log('  - 分组数据:', groups);
                console.log('  - 分组键名:', groupKeys);
                console.log('  - 当前分组索引:', this.currentIndex);
                console.log('  - 当前分组键名:', groupKeys[this.currentIndex % groupKeys.length]);
            }
            
            console.log('📊 计算属性:');
            console.log('  - displayItems:', this.displayItems);
            console.log('  - displayItems.length:', this.displayItems.length);
            console.log('  - showChangeButton:', this.showChangeButton);
            
            console.log('🧪 文本提取测试:');
            if (this.displayItems.length === 0) {
                console.log('  ❌ 没有数据可显示');
            } else {
                this.displayItems.forEach((item, index) => {
                    const text = this.getItemText(item);
                    console.log(`  ${index + 1}. ${JSON.stringify(item)} -> "${text}"`);
                    if (!text || text === '未知内容') {
                        console.warn(`  ⚠️ 第${index + 1}项文本提取失败!`);
                    }
                });
            }
            console.log('===============================');
        },

        problemClick(name) {
            this.$emit('itemClick', name);
        },
        onChange() {
            if (!this.supportChange || !this.isGroupedData) {
                console.log('🔍 不支持换一换功能');
                return;
            }
            
            const groups = this.getGroups();
            const groupKeys = Object.keys(groups);
            
            if (groupKeys.length < 2) {
                console.log('🔍 分组数量不足，无需换一换');
                return;
            }
            
            // 切换到下一个分组
            this.currentIndex = (this.currentIndex + 1) % groupKeys.length;
            
            console.log('🔍 换一项:', {
                currentIndex: this.currentIndex,
                currentGroup: groupKeys[this.currentIndex],
                totalGroups: groupKeys.length
            });
            
            // 触发换一换事件
            this.$emit('change', {
                index: this.currentIndex,
                group: groupKeys[this.currentIndex],
                data: groups[groupKeys[this.currentIndex]]
            });
        }
    }
};
</script>

<style lang="scss" scoped>
@include b(guess) {
    // margin: 28rpx 30rpx 40rpx;
    border-radius: 12px;
    opacity: 0.95;
    // border: 1.5px solid #ffffff;
	border: 1px solid #FFFFFF;
    overflow: hidden;
    background-size: cover !important;
    background-repeat: no-repeat !important;
	background-image: url(https://img.yummall.cn/baiyetong/byt-uni-ui/whiteMeng2222.svg);
	background-size: cover !important;
	background-repeat: no-repeat !important;
	z-index: 99;


    @include e(title) {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 16rpx 32rpx 16rpx;

        @include eb(left) {
            display: flex;
            align-items: center;

            @include e(icon) {
                margin: 0 4px;
                font-size: 28rpx;
                color: #303133;
            }
        }

        @include eb(right) {
            position: relative;
            display: flex;
            align-items: center;
            justify-content: flex-end;
            // padding-left: 18rpx;
            z-index: 10;
            // padding-right: 20rpx;
            width: 160rpx;
            // height: 30px;
            // transform: translate(32rpx, 6px);

            // background-image: url(https://img.yummall.cn/baiyetong/byt-uni-ui/whiteMeng3333.svg);
            background-size: cover !important;
            background-repeat: no-repeat !important;
            box-sizing: content-box !important;

            @include e(icon) {
                margin-left: 8rpx;
                font-size: 28rpx;
                color: #1890ff;
                position: relative;
                z-index: 10;
            }
        }
    }

    @include e(tab) {
        border-radius: 24rpx 0 24rpx 24rpx;
        // background: -webkit-linear-gradient(top, #dff6ff3d 100rpx, #dff6ffed);
        // background: rgba(255, 255, 255, 0.45);
        // border-top: 1.5px solid #ffffff;
        // background-image: url(https://img.yummall.cn/baiyetong/byt-uni-ui/whiteMeng2222.svg);
        // background-size: cover !important;
        // background-repeat: no-repeat !important;
        padding: 24rpx 0 8rpx;
        display: flex;
        flex-direction: column;

        @include eb(box) {
            display: flex;
            flex-direction: row;
            // padding: 0 24rpx;
            grid-gap: 8rpx;
            margin-bottom: 28rpx;
        }
        @include eb(btn) {
            // width: 146rpx;
            padding: 0 24rpx;
            height: 54rpx;
            border-radius: 8rpx;
            border: 1px solid #909193;
            color: #909193;
            margin-right: 14rpx;
            flex-shrink: 0;
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;

            text {
                font-size: 28rpx;
            }

            &.is-active {
                background: #1890ff;
                color: white;
                border-color: #1890ff;
            }

            &:last-child {
                margin-right: 0;
            }
        }
    }

    @include e(tabpane-item) {
        margin: 0 24rpx 16rpx;
        padding: 16rpx 24rpx;
        display: flex;
        align-items: center;
        border-radius: 20rpx;
        background: #ffffff;

        @include e(index) {
            font-size: 28rpx;
            flex-grow: 1;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
            padding-right: 10rpx;
            color: #3d3d3d;
        }

        &:last-child {
            border-bottom: 0;
        }
    }
}
</style>
